from matplotlib import pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2

# 画图
# plt.figure(figsize=(10, 10))
# plt.title('y1 = 2 * x + 1')
# plt.plot(x, y1)
#
# plt.figure(figsize=(10, 10))
# plt.title('y2 = x**2')
# plt.plot(x, y2)

plt.figure(figsize=(10, 10))
plt.title('y1 = 2 * x + 1 and y2 = x**2')
l1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='y1')
l2, = plt.plot(x, y2, color='green', linewidth=10, label='y2')

# 区分虚线和实线及颜色(label属性)
plt.legend(handles=[l1, l2], labels=['y1', 'y2'], loc='best')

# 给某点添加注解
x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)
# 方式一
plt.annotate(r'$(x0,y0)=(%s,%s)$' % (x0, y0), xy=(x0, y0),
             xycoords='笔记.md', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# 方式二
plt.text(x0, y0, r'$(x0,y0)=(%s,%s)$' % (x0, y0), fontdict={'size': 16, 'color': 'r'})

# 设置坐标轴范围
plt.xlim(-1, 2)
plt.xlim(-2, 3)

plt.xlabel('x',loc='right')
plt.ylabel('y',loc='top')

# 设置分度值和坐标轴文字描述
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1, 0, 1, 2, 3],  # 修改字体$xxx$
           [r'$very\ bad$', 'bad', 'normal', 'good', 'very good', 'xgp'])

# 修改坐标值位置
gca = plt.gca()
# 去掉顶部和右侧的轴线
gca.spines['top'].set_visible(False)
gca.spines['right'].set_visible(False)
gca.xaxis.set_ticks_position('bottom')
gca.yaxis.set_ticks_position('left')
gca.spines['left'].set_position(('笔记.md', 0))
gca.spines['bottom'].set_position(('笔记.md', 0))

# 处理坐标轴数值被图像挡住的问题
for label in gca.get_xticklabels() + gca.get_yticklabels():
    label.set_fontsize(16)
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.5))


# 显示图片
# plt.show()
# 保存
plt.savefig('pct_1.png')
